<?php

namespace App\Http\Controllers\Api;

use App\Models\SysUser;
use Illuminate\Support\Facades\Auth;

/**
 * 用户控制器
 * @package App\Http\Controllers\Api
 */
class UserController extends BaseController
{
    /**
     * 登陆请求
     * @param \App\Http\Requests\ApiUserLoginPost $request
     * @return \Illuminate\Http\Response
     */
    public function login(\App\Http\Requests\ApiUserLoginPost $request)
    {
        if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
            $user = Auth::user();
            $data['token'] = $user->createToken('MyApp')->accessToken;
            return $this->showMsg('success', '登陆成功', $data);
        } else {
            return $this->showMsg('error','登陆失败');
        }
    }

    /**
     * 注册
     * @param \App\Http\Requests\ApiUserRegisterPost $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(\App\Http\Requests\ApiUserRegisterPost $request)
    {
        try{
            $input = $request->all();
            $input['password'] = bcrypt($input['password']);
            $user = SysUser::create($input);
            $data['token'] = $user->createToken('MyApp')->accessToken;
            $data['name'] = $user->name;
            return $this->showMsg('success', '注册成功', $data);
        }catch (\Exception $e){
            return $this->showMsg('error','注册失败:'. $e->getMessage());
        }
    }

    /**
     * 获取用户数据
     * @return \Illuminate\Http\Response
     */
    public function get()
    {
        try{
            $user = Auth::user();
            return $this->showMsg('success', '获取成功', $user);
        }catch (\Exception $e){
            return $this->showMsg('error','获取失败:'. $e->getMessage());
        }
    }
}
